import json
from pprint import pprint
from fastapi import APIRouter, Request, Response
from fastapi.logger import logger
from src.utils.tools import json_loads
from src.utils.http.answer.typings import ExamDetail, UserExam, ParsedExamResult
from src.typings import APIResponse
from src.utils.config import DATA_DIR, global_config
from src.utils.prompt import render_prompt
from src.schemas import UserAnswer
from src.utils import client_create
from src.utils.http import ExamResult

# 导入聊天路由
from .chat import router as chat_router

api_v1 = APIRouter()

# 注册聊天路由
api_v1.include_router(chat_router)


@api_v1.get("/exams/result", response_model=APIResponse)
async def analyze_exam_result(request: Request):
    if user_exams_id := request.query_params.get("userExamID"):
        try:
            exam_result = await ExamResult(user_exams_id, dict(request.headers)).get_exam_result()
        except ValueError as e:
            # 上游服务返回 data 为 None 或其他可读错误，返回友好错误给客户端
            logger.error("Upstream error when fetching exam result: %s", str(e))
            return APIResponse(code=502, data=None, msg=str(e))
        result_file = DATA_DIR.joinpath(f"{user_exams_id}.json")

        # 检查结果文件是否存在
        if result_file.exists() and global_config.cache_answer:
            result_data = json_loads(result_file.read_text(encoding="utf-8"))
            return APIResponse(code=200, data=result_data, msg="success")

        # 如果不存在则AI解析
        result_data = {}

        messages: list = [
            {
                "role": "system",
                "content": render_prompt(
                    "answer.jinja",
                    json_schema=json.dumps(
                        ParsedExamResult.model_json_schema(), ensure_ascii=False
                    ),
                ),
            },
            {
                "role": "user",
                "content": f"请分析以下考试结果：{exam_result.model_dump()}",
            },
        ]

        while True:
            try:

                response = await client_create(messages)
                content = response.choices[0].message.content
                result_data = json_loads(content or "")
                logger.info("Parsed exam result data: %s", result_data)
                break
            except Exception as e:
                # 将异常信息加入到messages中告知机器人解析遭遇的错误
                messages.extend(
                    [
                        {
                            "role": "assistant",
                            "content": content,
                        },
                        {
                            "role": "user",
                            "content": f"输出的结果无法解析，请检查输出格式是否正确。错误信息：{str(e)}",
                        },
                    ]
                )
                print("Error occurred while parsing exam result:", e)
                continue

        DATA_DIR.joinpath(f"{user_exams_id}.json").write_text(
            json.dumps(result_data, ensure_ascii=False),
            encoding="utf-8",
        )
        return APIResponse(code=200, data=result_data, msg="success")
    else:
        return APIResponse(code=400, data=None, msg="userExamID is required")
